/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.adapter.http;

import han.bashe.business.adapter.Params;
import han.bashe.common.converter.HttpConverter;
import han.bashe.common.exception.BasheErrorCode;
import han.bashe.common.exception.BasheException;
import han.bashe.common.message.NormalizedMessage;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;

import v1.query.web.bifang.han.HttpBindingDocument.HttpBinding;

/**
 * @Author Kent
 */
public class HttpAdapter {

	public static NormalizedMessage call(NormalizedMessage req, HttpBinding b,
			Params params) throws BasheException {
		try {
			PostMethod post = null;

			HttpClient httpclient = new HttpClient();

			post = new PostMethod(b.getUrl());

			
			HttpClientParams ps = new HttpClientParams();
			ps.setSoTimeout(params.getTimeout() * 1000);
			httpclient.setParams(ps);
			
			String body = HttpConverter.toHttpRequest(req, post);
			RequestEntity entity = new StringRequestEntity(body, "text/xml",
					"UTF-8");
			
			post.setRequestEntity(entity);

			int result = httpclient.executeMethod(post);
			
			NormalizedMessage res = HttpConverter.toNormalized(post,false);
			
			if (result != 200) {
				throw new BasheException(BasheErrorCode.CALL_HTTP_ERROR,
						"Server returns HTTP code " + result  + " \n response string is \n" + res.getBody() );
			}
			return res;
		} catch (Exception e) {
			throw new BasheException(BasheErrorCode.UNKNOWN_ERROR,"unknown error",e);
		}

	}
}
